package il.ac.braude.sona.gui.forms.questions;

import java.awt.Color;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/**
 * Class in charge of number  fields questions GUI
 * @author  Ofek Ron
 * @author Avihay Avitan
 * @author Nitzan Inbar
 * @author Sasha Rozenthal
 * Laboratory in Software Engineering,Ort Braude College.</p>
 *
 */
@SuppressWarnings("serial")
public class QNumberField extends FormQuestion {
	private JTextField tf = new JTextField(20);
	private JLabel q;

	/**
	 * Class constructor.
	 * @param question
	 */
	public QNumberField(String question) {
		super(BoxLayout.X_AXIS);
		init(question);


	}
/**
 * Initializes question.
 * @param question
 */
	private void init(String question) {
		q = new JLabel(question);
		add(q);
		add(Box.createHorizontalGlue());
		add(tf);
		tf.setDocument(new PlainDocument() {
			@Override
			public void insertString(int offs, String str,
					AttributeSet a) throws BadLocationException {
			    if (str == null || str.length()==0) return;
			    if (Character.digit(str.charAt(0),10)!=-1) {
		    		super.insertString(offs, str.charAt(0)+"", a);
		    		insertString(offs+1,str.substring(1), a);
		    	}
		    	else insertString(offs,str.substring(1), a);
			}
		});
	}
/**
 * Class constructor.
 * @param question
 * @param necessity
 */
	public QNumberField(String question, boolean necessity) {
		super(BoxLayout.X_AXIS, necessity);
		init(question);
	}
/**
 * Makes field editable.
 * @param isEditable
 */
	public void setEditable(boolean isEditable) {
		tf.setEditable(isEditable);
	}
	/**
	 * Sets field's columns.
	 * @param columns
	 */
	public void setColumns(int columns) {
		tf.setColumns(columns);
	}
/**
 * Sets background color.
 * @param color
 */
	public void setBackgroudColor(Color color) {
		tf.setBackground(color);
	}
	@Override
	public void setDefaultAnswer(Object defaultAnswer) {
		tf.setText(defaultAnswer.toString());
	}

	@Override
	public Object getAnswer() {
		String answer = tf.getText();
		return (isNecessary() && answer.length()<=0) ? null : answer;
	}
	@Override
	public void markQuestion() {
		q.setForeground(Color.red);
		this.requestFocus();
	}
	@Override
	public void unmarkQuestion() {
		q.setForeground(Color.black);
	}
}
